package decomposition;

import matrix_operations.Matrix;
import direct_methods_for_systems_solver.GaussElimination;

public abstract class DecompositionLU {
	
	private static String msg ="";

	public static Matrix[] factorizing(Matrix A) {

		if (A.getN() != A.getM()) {
			msg = "Erro! The matrix can not be factored, because is not a square matrix.";
			System.out.println(msg);
			return null;
		}

		int n = A.getN();

		// initialize the matrix L and U
		Matrix L = Matrix.getIdentityMatrix(n);
		Matrix U = Matrix.getIdentityMatrix(n);

		for (int k = 0; k < n; k++) {

			U.setValue(k, k, A.getValue(k, k));

			for (int i = k + 1; i < n; i++) {

				if (A.getValue(k, k) == 0) {
					msg = "Erro! The Matrix cannot be factored with LU method";
					System.out.println(msg);
					return null;
				}
				L.setValue(i, k, A.getValue(i, k) / A.getValue(k, k));
				U.setValue(k, i, A.getValue(k, i));
			}

			for (int i = k + 1; i < n; i++) {

				for (int j = k + 1; j < n; j++) {

					A.setValue(i, j, A.getValue(i, j) - L.getValue(i, k)
							* U.getValue(k, j));
				}

			}
		}

		return (new Matrix[] { L, U });
	}

	public static Matrix solveSysem(Matrix[] LU, Matrix B) {
		msg = "";
		
		if (LU == null){
			msg = "Error, this matrix is singular!";
			return null;
		}		
		
		Matrix y = GaussElimination.solveSystem(LU[0], B);
		return GaussElimination.solveSystem(LU[1], y);
	}
	
	public static String getMsg(){
		return msg;
	}
}
